<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <!-- <el-form-item prop="date">
        <el-date-picker
          v-model="queryParams.date"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item> -->
      <el-form-item prop="sysDeptList">
        <cascader-select
          v-model="queryParams.sysDeptList"
          :values="queryParams.sysDeptList"
          varient="energy"
          node-key="id"
          size="small"
          :filterable="true"
          placeholder="请选择用能单位"
        ></cascader-select>
      </el-form-item>

      <el-form-item prop="energyType">
        <el-select
          v-model="queryParams.energyType"
          placeholder="请选择能耗类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.energy_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="subentryType">
        <el-select
          v-model="queryParams.subentryType"
          placeholder="请选择分项类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.subentry_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
        <el-button type="primary" plain size="small" @click="handleExport"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <!-- :header-cell-style="tableHeaderCellStyle"
      :header-cell-class-name="headerRowStyle"
      :cell-style="cellStyle" -->
    <el-table v-loading="loading" max-height="600" :data="list" border>
      <el-table-column
        prop="deptName"
        label="用能单位"
        min-width="200"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <!-- <el-table-column
        prop="deptName"
        label="能耗节气"
        min-width="120"
        show-overflow-tooltip
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="year"
        label="统计年份"
        min-width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="energyVal"
        label="实际能耗A（kwh）"
        min-width="100"
        show-overflow-tooltip
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="energyType"
        label="能耗类型"
        min-width="120"
        show-overflow-tooltip
        align="center"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.energy_type"
            :value="scope.row.energyType"
            class="tag"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="energyValFee"
        label="实际费用M（元）"
        min-width="150"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="budgetFee"
        label="能耗预算N（元）"
        min-width="150"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="adjustFee"
        label="预算年中调整P（元）"
        min-width="180"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="surplusFee"
        label="预算年终盈利X（元 X=N+P-M）"
        min-width="250"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <!-- <el-table-column
        prop="energyExtremumTotal"
        label="极值能耗分项"
        align="center"
      >
        <el-table-column
          prop="energyExtremumType"
          label="分项"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="energyExtremumTotal"
          label="能耗（kgce）"
          width="120"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column
        prop="energyCo2Total"
        label="总能耗折算CO2（tCO2）"
        width="200"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="energyAreaTotal"
        label="单位面积电耗(kwh/m2)"
        width="180"
        align="center"
      >
      </el-table-column> -->
      <!-- <el-table-column label="约束额度" align="center">
        <el-table-column prop="constraintVal" label="额度值" align="center">
        </el-table-column>
        <el-table-column
          prop="constraintValExceed"
          label="超额能耗"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="constraintValExceedCo2Total"
          label="超额能耗折算CO2（kgCO2）"
          width="240"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column label="基准额度" align="center">
        <el-table-column prop="baseVal" label="额度值" align="center">
        </el-table-column>
        <el-table-column
          prop="baseValExceed"
          width="120"
          label="超额能耗"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="baseValExceedCo2Total"
          label="超额能耗折算CO2（kgCO2）"
          width="240"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column label="引导额度" align="center">
        <el-table-column prop="guideVal" label="额度值" align="center">
        </el-table-column>
        <el-table-column
          prop="guideValExceed"
          label="超额能耗"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="guideValExceedCo2Total"
          label="超额能耗折算CO2（kgCO2）"
          width="240"
          align="center"
        >
        </el-table-column>
      </el-table-column> -->
      <!-- <el-table-column
        prop="green"
        label="碳中和建议方案（基于基准值超支金额）"
        width="900"
        fixed="right"
        align="center"
      >
        <template slot-scope="scope">
          <div class="table">
            <div
              v-for="(item, index) in scope.row.plans"
              :key="index"
              class="table-item"
            >
              <div class="title">{{ item.planName }}</div>
              <div
                v-for="(it, idx) in item.children"
                :key="idx"
                class="content"
              >
                <template v-if="it.checked">
                  <span> {{ it.energyName }}</span>
                  <span>总价：{{ it.measureTotalFee }}</span>
                  <span>单价：{{ it.measurePrice }}</span>
                  <span>数量：{{ it.measureNum }}</span>
                </template>
              </div>
            </div>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="status"
        label="确认状态"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.energy_carbon_neutral_status"
            :value="scope.row.status"
            class="tag"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="300"
        prop="caozuo"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 0"
            v-hasPermi="['energy:neutralNeutral:audit:0']"
            size="small"
            type="text"
            @click="handleAudit(scope.row, 'show0')"
            >预算年中调整</el-button
          >
          <el-button
            v-if="scope.row.status === 0"
            v-hasPermi="['energy:neutralNeutral:audit:0']"
            size="small"
            type="text"
            @click="handleReport(scope.row.id)"
            >申报</el-button
          >
          <el-button
            v-else-if="scope.row.status === 1"
            v-hasPermi="['energy:neutralNeutral:audit:1']"
            size="small"
            icon="el-icon-document-checked"
            type="text"
            @click="handleAudit(scope.row, 'show1')"
            >能耗考核</el-button
          >
          <el-button
            v-else-if="scope.row.status === 2"
            v-hasPermi="['energy:neutralNeutral:audit:2']"
            size="small"
            type="text"
            @click="handleAudit2(scope.row.id, '年中调整审批')"
            >年中调整审批</el-button
          >
          <template v-else-if="scope.row.status === 3">
            <el-button
              v-hasPermi="['energy:neutralNeutral:confirm']"
              size="small"
              type="text"
              @click="handleConfirm(scope.row)"
              >碳中和申报</el-button
            >
            <el-button
              v-hasPermi="['energy:neutralNeutral:audit:3']"
              size="small"
              type="text"
              @click="handleAudit2(scope.row.id, '碳中和审批')"
              >碳中和审批</el-button
            >
          </template>
          <el-button size="small" type="text" @click="detail(scope.row.id)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :page-sizes="[20, 40, 60, 80]"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 年中调整对话框 -->
    <el-dialog
      title="预算年中调整"
      :visible.sync="show0"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form0"
        :model="model"
        :rules="rules"
        label-width="100px"
        class="mt20"
      >
        <el-form-item label="调整金额" prop="adjustFee">
          <el-input-number v-model="model.adjustFee" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="model.remark"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEdit('form0')">确 定</el-button>
        <el-button @click="handleClose('show0')">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 能耗考核对话框 -->
    <el-dialog
      title="能耗考核"
      :visible.sync="show1"
      width="500px"
      append-to-body
    >
      <el-form ref="form1" :model="model" :rules="rules" label-width="120px">
        <el-form-item label="考核盈余状态" prop="surplusStatus">
          <el-select
            v-model="model.surplusStatus"
            placeholder="请选择考核盈余状态"
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.energy_carbon_neutral_surplus_status"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
            <!-- v-if="Number(dict.value) > 0" -->
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="content">
          <el-input type="textarea" v-model="model.content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form1')">确 定</el-button>
        <el-button @click="handleClose('show1')">取 消</el-button>
      </div>
    </el-dialog>
    <operate :visible.sync="show" :data="data" @close="close"></operate>
    <detail :id="id" :visible.sync="detailShow" @close="close"></detail>
  </lb-layout>
</template>

<script>
import { list, audit, adjustFee } from "@/api/carbonNeutral/government";
import CascaderSelect from "@/components/Select/CascaderSelect";
import operate from "@/views/work/government/components/operate";
import detail from "@/views/work/government/components/detail";
import { exportExecl } from "@/utils/export-execl";

export default {
  name: "government",
  dicts: [
    "energy_type",
    "energy_clean_power",
    "energy_green_power",
    "energy_carbon_power",
    "energy_saving_target",
    "energy_carbon_neutral_status",
    "energy_carbon_neutral_surplus_status",
  ],
  components: { CascaderSelect, exports, operate, detail },
  data() {
    return {
      id: "",
      data: {
        id: null,
        plans: [],
      },
      show0: false,
      show1: false,
      detailShow: false,
      model: {
        adjustFee: 0,
        remark: "",
        surplusStatus: "",
      },
      rules: {
        remark: [
          {
            required: true,
            message: "请输入备注",
          },
        ],
        adjustFee: [
          {
            required: true,
            message: "请输入调整金额",
            trigger: ["change", "blur"],
          },
        ],
        surplusStatus: [
          {
            required: true,
            message: "请选择考核盈余状态",
            trigger: ["change", "blur"],
          },
        ],
      },
      show: false,
      // 遮罩层
      loading: false,
      // 表格树数据
      list: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sysDeptList: [],
        energyType: "",
        // date: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    detail(id) {
      this.id = id;
      this.detailShow = true;
    },
    handleAudit(data, show) {
      console.log(data, "dadada");
      console.log(
        this.dict.type.energy_carbon_neutral_surplus_status,
        "dict.type.energy_carbon_neutral_surplus_status"
      );
      this[show] = true;
      this.model = data;
    },
    //申报
    handleReport(id) {
      this.$prompt("请输入申报理由", "预算申报", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "申报理由不能为空",
      })
        .then(({ value }) => {
          const data = {
            remark: value,
            id,
            auditEvent: 1,
          };
          audit(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.getList();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300093");
            });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "取消输入",
          // });
        });
    },
    //碳中和审批
    handleAudit2(id, msg) {
      this.$prompt("请输入审批意见", msg, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "审批意见不能为空",
      })
        .then(({ value }) => {
          const data = {
            remark: value,
            id,
            auditEvent: 2,
          };
          audit(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.getList();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300093");
            });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "取消输入",
          // });
        });
    },
    /** 提交按钮 */
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const data = {
            ...this.model,
            auditEvent: 2,
          };
          if (this.model.surplusStatus == 0) {
            this.$message({
              message: "考核盈余状态不能为未考核",
              type: "warning",
            });
          } else {
            audit(data)
              .then((res) => {
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose("show1");
                this.getList();
              })
              .catch((err) => {
                this.$store.commit("app/updateApiCount");
                // this.$message.error("系统错误,请联系管理员!300075");
              });
          }
        }
      });
    },
    handleEdit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const data = {
            id: this.model.id,
            adjustFee: this.model.adjustFee,
          };
          adjustFee(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.show0 = false;
              this.getList();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300075");
            });
        }
      });
    },
    handleClose(show) {
      this[show] = false;
    },
    headerRowStyle(obj) {
      if (obj.column.property === "status") {
        return "tabel-bg-red";
      } else if (obj.column.property === "green") {
        return "tabel-bg-green";
      } else if (obj.column.property === "caozuo") {
        return "tabel-bg-blue";
      }
    },
    tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 11 || columnIndex === 12 || columnIndex === 13) {
        return "background:rgba(223,240,216,0.4)";
      }
    },
    //设置指定行、列、具体单元格颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      //指定坐标rowIndex ：行，columnIndex ：列
      if (columnIndex === 17) {
        return "background:rgba(223,240,216,0.4)";
      } else if (columnIndex === 18) {
        return "background:rgba(242,222,222,0.4)";
      } else if (columnIndex === 19) {
        return "background:rgba(217,237,247,0.4)";
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const { date, sysDeptList, ...other } = this.queryParams;
      // const [startTime, endTime] = date || [];
      const data = {
        // startTime,
        // endTime,
        deptId: sysDeptList[sysDeptList.length - 1],
        ...other,
      };
      exportExecl("额度预算", "/energy/budget-manage/export", data, this);
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      const { date, sysDeptList, ...other } = this.queryParams;
      // const [startTime, endTime] = date || [];
      const data = {
        // startTime,
        // endTime,
        deptId: sysDeptList[sysDeptList.length - 1],
        ...other,
      };
      list(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.list = res.rows.map((item) => {
            item.cleanEnergys = item.cleanEnergyList
              ? item.cleanEnergyList.split(",")
              : [];
            item.greenPowers = item.greenPowerList
              ? item.greenPowerList.split(",")
              : [];
            item.carbonSinks = item.carbonSinkList
              ? item.carbonSinkList.split(",")
              : [];
            return item;
          });
          this.total = res.total;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300091");
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    close(status) {
      this.show = false;
      this.detailShow = false;
      setTimeout(() => {
        if (status) this.getList();
      }, 200);
    },
    /** 人工确认 */
    handleConfirm(row) {
      this.show = true;
      const { plans, id } = row;
      const data = {
        id,
        plans,
      };
      this.data = data;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .tabel-bg-green {
  background: rgba(223, 240, 216, 0.4) !important;
}

::v-deep .tabel-bg-blue {
  background: rgba(217, 237, 247, 0.4) !important;
}

::v-deep .tabel-bg-red {
  background: rgba(242, 222, 222, 0.4) !important;
}
.table {
  display: flex;
  justify-content: space-between;
  .table-item {
    margin: 0 20px;
    .title {
      color: #515a6e;
      font-weight: bold;
      text-align: center;
    }
    .content {
      text-align: left;
      span {
        font-size: 15px;
        display: inline-block;
        margin: 0 2px;
      }
    }
  }
}
</style>
